package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApUserFeign;
import com.heima.feigns.ArticleFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    ApUserFeign apUserFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //检验用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("请登录后进行评论");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据userId远程调用用户信息
        ApUser apUser = apUserFeign.findApUserById(user.getId());
        //判断当前用户是否存在
        if (apUser == null) {
            log.error("找不到当前用户");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前登录的用户不存在");
        }
        //根据文章id查询当前文章是否存在
        ResponseResult<ApArticle> apArticById = articleFeign.findApArticById(String.valueOf(dto.getArticleId()));
        ApArticle artic = apArticById.getData();
        if (artic == null) {
            log.error("当前文章不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断评论内容长度
        if (dto.getContent().length() > 140) {
            log.error("评论内容不得大于140字");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "内容大于140字符");
        }
        //创建评论实体,保存评论信息
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setChannelId(artic.getChannelId());
        apComment.setContent(dto.getContent());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        //保存到数据库中
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //1 校验参数
        ResponseResult<ApArticle> apArticById = articleFeign.findApArticById(String.valueOf(dto.getArticleId()));
        ApArticle artic = apArticById.getData();
        if (artic == null) {
            log.error("当前文章不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断显示条数
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //   ========================需要变更处 start =============================
        //2 查询Mongo文章所有评论列表
        List<ApComment> apCommentList = null;
        if (dto.getIndex().intValue() == 1) { // 判断当前是否是第一页评论
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short) 1));
            Sort sort = Sort.by(Sort.Direction.DESC, "likes");
            query.with(sort);// 排序
            apCommentList = mongoTemplate.find(query, ApComment.class);
            // 新size = size - 热评数量
            dto.setSize(dto.getSize() - apCommentList.size());
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query query1 = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short) 0));
            Sort sort1 = Sort.by(Sort.Direction.DESC, "createdTime");
            query1.with(sort1).limit(dto.getSize());// 排序
            List<ApComment> apComments1 = mongoTemplate.find(query1, ApComment.class);
            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            apCommentList.addAll(apComments1);
        } else {
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
            //TODO:显示评论
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()).and("flag").is((short)0));
            //设置排序
            Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
            query.with(sort).limit(dto.getSize());
            apCommentList = mongoTemplate.find(query, ApComment.class);
        }
        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //没有登录,直接返回评论信息
            return ResponseResult.okResult(apCommentList);
        } else {
            //创建评论集合,用于封装查询出来的所有评论
            List<ApCommentVo> apCommentVos = new ArrayList<>();
            for (ApComment comment : apCommentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment, apCommentVo);
                //根据用户id,文章id查询是否有点赞记录
                boolean b = findCommentLikeByCommntIdAndApUserId(comment.getId(), user.getId());
                if (b) {
                    apCommentVo.setOperation((short) 0);
                }
                apCommentVos.add(apCommentVo);
            }
            System.out.println("封装后的" + apCommentVos);
            return ResponseResult.okResult(apCommentVos);
        }
    }     // ========================需要变更处 end =============================
        //根据文章id查询当前文章是否存在




    private boolean findCommentLikeByCommntIdAndApUserId(String id, Integer apUserId) {
        Query query = Query.query(Criteria.where("authorId").is(apUserId).and("commentId").is(id));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        if (one != null){
            return true;
        }
        return false;
    }

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //检验用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            log.error("请登录后进行评论点赞");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据评论id查询当前评论是否村咋I
        ApComment comment = findCommentById(dto.getCommentId());
        if (comment == null){
            log.error("评论数据不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"评论数据不存在");
        }
        //判断操作类型
        if (dto.getOperation() != 0 && dto.getOperation() != 1){
            log.error("操作类型只能为点赞或取消点赞(0/1)");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"操作类型不合法");
        }
        //设置一个点赞数
        Integer likes = null;
        //根据操作类型做出判断
        if (dto.getOperation() == 0){   //点赞
            //查询是否有点赞记录 没有则生成,有则提示不能重复点赞
            likes = saveCommentLikeByAuthorIdAndCommentId(user.getId(),dto.getCommentId());
        }else if (dto.getOperation() == 1) { // 取消点赞
             likes = removeCommentLikeByAuthorIdAndCommentId(user.getId(), dto.getCommentId());
        }

        Map map = new HashMap();
        map.put("likes", likes);
        //判断点赞数是否>10且为普通评论
        if (likes >= 10 && comment.getFlag()==0){
            commentHotService.hotCommentExecutor(comment);
        }
        return ResponseResult.okResult(map);
    }
    private Integer removeCommentLikeByAuthorIdAndCommentId(Integer ApUserId, String commentId) {
        //根据用户id,评论id查询点赞记录是否存在
        Query query = Query.query(Criteria.where("authorId").is(ApUserId).and("commentId").is(commentId));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        if (one != null){
            //删除点赞记录
            mongoTemplate.remove(query, ApCommentLike.class);
            //修改点赞数量
            ApComment comment = findCommentById(commentId);
            //在原有的点赞数上+1
            Integer likes = comment.getLikes()-1;
            if (likes < 0 ){
                log.error("点赞数量不能小于0");
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            //设置新的点赞数
            comment.setLikes(likes);
            //保存新的点赞记录
            mongoTemplate.save(comment);
            //返回最新的点赞数量
            return likes;
        }else{
            log.error("点赞记录不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            return null;
        }
    }

    @Autowired
    RedissonClient redissonClient;

    private Integer saveCommentLikeByAuthorIdAndCommentId(Integer ApUserId, String commentId) {
        //根据用户id,评论id查询点赞记录是否存在
        RLock lock = redissonClient.getLock("likes-lock");
        Query query = Query.query(Criteria.where("authorId").is(ApUserId).and("commentId").is(commentId));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        lock.lock();
        try {
            if (one == null){
                //创建当前点赞记录
                ApCommentLike commentLike = new ApCommentLike();
                commentLike.setAuthorId(ApUserId);
                commentLike.setCommentId(commentId);
                commentLike.setOperation((short)0);
                mongoTemplate.save(commentLike);
                //根据评论id新增一条点赞记录
                ApComment comment = findCommentById(commentId);
                //在原有的点赞数上+1
                Integer likes = comment.getLikes()+1;
                //设置新的点赞数
                comment.setLikes(likes);
                //保存新的点赞记录
                mongoTemplate.save(comment);
                return likes;
            }else{
                log.error("请勿重复点赞");
                CustException.cust(AppHttpCodeEnum.DATA_EXIST);
            }
        } finally {
            lock.unlock();
        }
        return null;
    }

    /**
     * 根据评论Id查询评论数据
     * @param commentId
     * @return
     */
    public ApComment findCommentById(String commentId) {
        if (StringUtils.isEmpty(commentId)){
            log.error("评论id不能为空");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"评论id不能为空");
        }
        Query query = Query.query(Criteria.where("id").is(commentId));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        return apComment;
    }
}
